# coding: utf-8

from django.db.models import signals
from django.db import models
from datetime import datetime, date, time
from ddrbug.nivel.models import Nivel
from ddrbug.movimentacaobug.models import MovimentacaoBug

STATUS_DEFAULT  = u'01'
OPCAO_CHOICES   = ( ('A','Aprovado'),('R','Recusado') )
temMovimentacao = False

class Bug(models.Model):

    Codigo 		= models.AutoField(max_length=4, db_index=True, editable=False, primary_key=True)
    Status 		= models.CharField(max_length=2, default=STATUS_DEFAULT,editable=False)
    Solicitante = models.ForeignKey('solicitante.Solicitante')
    Descricao   = models.CharField(max_length=256)
    Opcao       = models.CharField(max_length=1,choices=OPCAO_CHOICES)
    DataInicio  = models.DateTimeField(editable=False)
    DataFim     = models.DateTimeField(editable=False,null=True)
    
    class Meta:
        unique_together = ['Codigo']

def bug_pre_save(signal, instance, sender, **kwargs):
    statusAtual = instance.Status
    # quando inserida, adiciono a hora.
    if (instance.Status == '01'):
        instance.DataInicio = datetime.now()
    # verifico qual o proximo nivel
    if (instance.Opcao == 'A'):
       instance.Status = Nivel.objects.filter(Status=instance.Status)[0].ProximoNivel
    else:
        instance.Status = Nivel.objects.filter(Status=instance.Status)[0].AnteriorNivel
    if (statusAtual == instance.Status):
        instance.DataFim = datetime.now()
    else:
        global temMovimentacao
        temMovimentacao = True

def bug_post_save(instance, **kwargs):
    if (temMovimentacao):
        a=MovimentacaoBug(CodBug=instance, Descricao=instance.Descricao, Data=datetime.now())
        a.save()

signals.pre_save.connect(bug_pre_save, sender=Bug)        
signals.post_save.connect(bug_post_save, sender=Bug)